package com.demo.personalaccountingbackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.personalaccountingbackend.dto.ApiResponse;
import com.demo.personalaccountingbackend.dto.RecordDTO;
import com.demo.personalaccountingbackend.dto.RecordRequest;
import com.demo.personalaccountingbackend.entity.AccountRecord;
import com.demo.personalaccountingbackend.mapper.AccountRecordMapper;
import com.demo.personalaccountingbackend.mapper.CategoryMapper;
import com.demo.personalaccountingbackend.service.RecordService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
@RequiredArgsConstructor
public class RecordServiceImpl extends ServiceImpl<AccountRecordMapper, AccountRecord> implements RecordService {

    private final AccountRecordMapper accountRecordMapper;
    private final CategoryMapper categoryMapper;

    @Override
    public ApiResponse getRecords(Long userId, LocalDate startDate, LocalDate endDate, Integer type) {
        try {
            List<RecordDTO> records;

            if (startDate != null && endDate != null) {
                records = accountRecordMapper.findRecordWithCategoryByUserIdAndDateRange(userId, startDate, endDate);
            } else if (type != null) {
                records = accountRecordMapper.findRecordWithCategoryByUserIdAndType(userId, type);
            } else {
                records = accountRecordMapper.findRecordWithCategoryByUserId(userId);
            }

            return ApiResponse.success("获取记录成功", records);
        } catch (Exception e) {
            return ApiResponse.error("获取记录失败: " + e.getMessage());
        }
    }

    @Override
    public ApiResponse getRecordDetail(Long id, Long userId) {
        try {
            RecordDTO record = accountRecordMapper.findById(id);

            if (record == null) {
                return ApiResponse.error("记录不存在");
            }

            // 使用 MyBatis-Plus 的条件构造器检查记录是否属于当前用户
            boolean exists = lambdaQuery()
                    .eq(AccountRecord::getId, id)
                    .eq(AccountRecord::getUserId, userId)
                    .exists();

            if (!exists) {
                return ApiResponse.error("无权访问此记录");
            }

            return ApiResponse.success("获取记录详情成功", record);
        } catch (Exception e) {
            return ApiResponse.error("获取记录详情失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public ApiResponse addRecord(RecordRequest recordRequest, Long userId) {
        try {
            // 验证分类是否存在
            if (categoryMapper.selectById(recordRequest.getCategoryId()) == null) {
                return ApiResponse.error("分类不存在");
            }

            AccountRecord record = new AccountRecord();
            record.setUserId(userId);
            record.setType(recordRequest.getType());
            record.setAmount(recordRequest.getAmount());
            record.setCategoryId(recordRequest.getCategoryId());
            record.setRemark(recordRequest.getRemark());
            record.setRecordDate(recordRequest.getRecordDate());
            record.setCreateTime(LocalDateTime.now());
            record.setUpdateTime(LocalDateTime.now());

            boolean success = save(record);
            if (success) {
                RecordDTO newRecord = accountRecordMapper.findById(record.getId());
                return ApiResponse.success("添加记录成功", newRecord);
            } else {
                return ApiResponse.error("添加记录失败");
            }
        } catch (Exception e) {
            return ApiResponse.error("添加记录失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public ApiResponse updateRecord(Long id, RecordRequest recordRequest, Long userId) {
        try {
            // 使用 MyBatis-Plus 的条件构造器检查记录是否存在且属于当前用户
            boolean exists = lambdaQuery()
                    .eq(AccountRecord::getId, id)
                    .eq(AccountRecord::getUserId, userId)
                    .exists();

            if (!exists) {
                return ApiResponse.error("记录不存在或无权限修改");
            }

            // 验证分类是否存在
            if (categoryMapper.selectById(recordRequest.getCategoryId()) == null) {
                return ApiResponse.error("分类不存在");
            }

            AccountRecord record = new AccountRecord();
            record.setId(id);
            record.setType(recordRequest.getType());
            record.setAmount(recordRequest.getAmount());
            record.setCategoryId(recordRequest.getCategoryId());
            record.setRemark(recordRequest.getRemark());
            record.setRecordDate(recordRequest.getRecordDate());
            record.setUpdateTime(LocalDateTime.now());

            // 使用 MyBatis-Plus 的更新方法
            boolean success = updateById(record);
            if (success) {
                RecordDTO updatedRecord = accountRecordMapper.findById(id);
                return ApiResponse.success("更新记录成功", updatedRecord);
            } else {
                return ApiResponse.error("更新记录失败");
            }
        } catch (Exception e) {
            return ApiResponse.error("更新记录失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public ApiResponse deleteRecord(Long id, Long userId) {
        try {
            // 使用条件构造器构建删除条件
            LambdaQueryWrapper<AccountRecord> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(AccountRecord::getId, id)
                    .eq(AccountRecord::getUserId, userId);

            boolean success = remove(wrapper);
            if (success) {
                return ApiResponse.success("删除记录成功");
            } else {
                return ApiResponse.error("删除记录失败");
            }
        } catch (Exception e) {
            return ApiResponse.error("删除记录失败: " + e.getMessage());
        }
    }

    @Override
    public ApiResponse getStatistics(Long userId, LocalDate startDate, LocalDate endDate) {
        try {
            if (startDate == null || endDate == null) {
                endDate = LocalDate.now();
                startDate = endDate.minusDays(30);
            }

            List<RecordDTO> statistics = accountRecordMapper.getStatisticsByDateRange(userId, startDate, endDate);
            return ApiResponse.success("获取统计信息成功", statistics);
        } catch (Exception e) {
            return ApiResponse.error("获取统计信息失败: " + e.getMessage());
        }
    }

    @Override
    public ApiResponse getMonthlyStatistics(Long userId, Integer year, Integer month) {
        try {
            if (year == null) year = LocalDate.now().getYear();
            if (month == null) month = LocalDate.now().getMonthValue();

            List<RecordDTO> statistics = accountRecordMapper.getMonthlyStatistics(userId, year, month);
            return ApiResponse.success("获取月度统计成功", statistics);
        } catch (Exception e) {
            return ApiResponse.error("获取月度统计失败: " + e.getMessage());
        }
    }

    /**
     * 使用 MyBatis-Plus 的条件构造器示例
     */
    public List<AccountRecord> getRecordsByCondition(Long userId, Integer type, LocalDate startDate, LocalDate endDate) {
        LambdaQueryWrapper<AccountRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AccountRecord::getUserId, userId)
                .eq(type != null, AccountRecord::getType, type)
                .ge(startDate != null, AccountRecord::getRecordDate, startDate)
                .le(endDate != null, AccountRecord::getRecordDate, endDate)
                .orderByDesc(AccountRecord::getRecordDate, AccountRecord::getCreateTime);

        return list(wrapper);
    }
}